#pragma once
#include "Common.h"
#include "ThreadCache.h"
#include "PageCache.h"
#include "ObjectPool.h"

///////////////////////////////////////////////////
static void* ConcurrentAlloc(size_t size)
{
	if (size > MAX_BYTES)
	{
		size_t alignSize = SizeClass::RoundUp(size);
		size_t numPage = alignSize >> PAGE_SHIFT;

		PageCache::GetInstance()->lock();
		Span* span = PageCache::GetInstance()->NewSpan(numPage);
		PageCache::GetInstance()->unlock();
		span->_alignSize = alignSize;

		void* ptr = (void*)(span->_pageId << PAGE_SHIFT);
		return ptr;
	}
	else
	{
		if (pTLSThreadCache == nullptr)
		{
			static ObjectPool<ThreadCache> tcPool;
			pTLSThreadCache = tcPool.New();
		}
		return pTLSThreadCache->Allocate(size);
	}
}

///////////////////////////////////////////////////
static void ConcurrentFree(void* ptr)
{
	Span* span = PageCache::GetInstance()->MapObjectToSpan(ptr);
	size_t size = span->_alignSize;

	if (size > MAX_BYTES)
	{
		
		PageCache::GetInstance()->lock();
		PageCache::GetInstance()->ReleaseSpanToPageCache(span);
		PageCache::GetInstance()->unlock();
	}
	else
	{
		assert(pTLSThreadCache);
		pTLSThreadCache->Dealloc(ptr, size);
	}
}